package com.panshi.service;

import com.panshi.api.IQuestionApi;
import com.panshi.mapper.IMessageMapper;
import com.panshi.mapper.IUserMapper;
import com.panshi.tool.MailUtils;
import com.panshi.vo.qa.DataResultQA;
import com.panshi.vo.qa.Messag;
import com.panshi.vo.qa.Question;
import com.panshi.vo.qa.ReplyAudit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ReplyAuditService {
    @Autowired
    IMessageMapper messageMapper;

    @Autowired
    IUserMapper userMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    IQuestionApi questionApi;


    //定义一个交换器名称（广播，扇形）
    public static final String EX_NAME="reply-audit-exchange-fanout";
    //定义一个交换器名称绑定的消息队列名称1
    public static final String SEND_MAIL="send-mail";
    //定义一个交换器名称绑定的消息队列名称2
    public static final String SEND_INTERIOR_MESSAGE="send-interior-message";

    /**
     *    发送消息到交换器中，然后交换器分发到绑定这个交换器的队列
     * @param replyAudit
     */
    public void send(ReplyAudit replyAudit) {
        //发送mq到一个交换器中，第一个参数是交换机名称，第二参数是路由器名称（这个名称可以指定或者为空字符串）
        rabbitTemplate.convertAndSend(EX_NAME,"", replyAudit);
    }

    /**
     * 创建第一个消息端监听器，绑定一个广播交换机以及队列名称
     * 如果下面的交换器名称，路由名称不存在，系统在启动的时候会自动创建
     * @param replyAudit
     */
    @RabbitListener(bindings = {
            @QueueBinding(value =@Queue(name = SEND_MAIL),//指定队列名称
                    exchange =@Exchange(name = EX_NAME,type = ExchangeTypes.FANOUT))//指定交换器名称且是一个扇形交换器，相关于一个广播
    })
    public void receiveFANOUT1(ReplyAudit replyAudit) {
        //获取用户id
        int userId = replyAudit.getRUserId();
        //查询用户邮箱
        String email = userMapper.queryMail(userId);

        //标题
        String title = "有贝口腔网 | 回答审核提醒";
        //内容
        String content = "";
        content += "<h1 style='width: 150px;margin: 0px auto;color: #009F95;'>回答审核消息</h1>";
        content += "<br/>";
        content += "<div  style='width: 300px;margin: 0px auto;'>您的回答:</div>";
        content += "<div  style='width: 300px;margin: 0px auto;'>《"+replyAudit.getRContent()+"》</div>";

        if(replyAudit.getRState() == 2){
            content += "<br/>";
            content += "<div  style='width: 300px;margin: 0px auto;'>审核通过啦 ^_^ !</div>";
        }else if(replyAudit.getRState() == 3){
            content += "<br/>";
            content += "<div  style='width: 300px;margin: 0px auto;'>审核没有通过 ~……~ !</div>";
        }

        try {
            MailUtils.sendMail(email,title,content);
            log.info("邮件发送成功！");
            log.info("email：{}",email);
            log.info("title：{}",title);
            log.info("content：{}",content);
        }catch (Exception e){
            e.printStackTrace();
            log.info("邮件发送失败 ~……~！");
        }

        //给问题发布者发送邮件
        receiveQuestionMail(replyAudit);
    }

    /**
     * 给问题发布者发送邮件
     * @param replyAudit
     */
    public void receiveQuestionMail(ReplyAudit replyAudit) {
        //审核通过时给发表问题的用户发送邮件
        if(replyAudit.getRState() == 2){
            //所属问题id
            int questionId = replyAudit.getRQuestionId();
            //查询问题信息
            DataResultQA<Question> dataResultQA = questionApi.inquireByIdQuestion(questionId);
            Question question = dataResultQA.getData();

            //获取用户id
            int userId = question.getQUserId();

            //问题内容
            String  questionContent = question.getQContent();
            //问题内容
            String replyContent = replyAudit.getRContent();

            //查询用户邮箱
            String email = userMapper.queryMail(userId);
            //标题
            String title = "有贝口腔网 | 提醒";
            //内容
            String content = "";
            content += "<h1 style='width: 220px;margin: 0px auto;color: #009F95;'>有人回答了您的问题</h1>";
            content += "<br/>";
            content += "<div  style='width: 300px;margin: 0px auto;'>您的提问:</div>";
            content += "<div  style='width: 300px;margin: 0px auto;'>《"+questionContent+"》</div>";
            content += "<br/>";
            content += "<div  style='width: 300px;margin: 0px auto;'>回答:</div>";
            content += "<div  style='width: 300px;margin: 0px auto;'>《"+replyContent+"》</div>";

            try {
                MailUtils.sendMail(email,title,content);
                log.info("邮件发送成功！");
                log.info("email：{}",email);
                log.info("title：{}",title);
                log.info("content：{}",content);
            }catch (Exception e){
                e.printStackTrace();
                log.info("邮件发送失败 ~……~！");
            }

        }

    }


    /**
     * 创建第二消息端监听器，绑定一个广播交换机以及队列名称
     * @param replyAudit
     */
    @RabbitListener(bindings = {
            @QueueBinding(value =@Queue(name = SEND_INTERIOR_MESSAGE),//指定队列名称
                    exchange =@Exchange(name = EX_NAME,type = ExchangeTypes.FANOUT))//指定交换器名称且是一个扇形交换器，相关于一个广播
    })
    public void receiveFANOUT2(ReplyAudit replyAudit) {
        //创建站内消息
        Messag messag = new Messag();

        //所属问题id
        int questionId = replyAudit.getRQuestionId();
        //查询问题信息
        DataResultQA<Question> dataResultQA = questionApi.inquireByIdQuestion(questionId);
        Question question = dataResultQA.getData();

        //问题内容
        String title = question.getQContent();
        messag.setTitle(title);
        //回答内容
        String content = replyAudit.getRContent();
        messag.setContent(content);
        //审核状态
        int checkState = replyAudit.getRState();
        messag.setCheckState(checkState);
        //站内消息类型（0:公共 1:问题 2:回答 3:文章）
        int checkType = 2;//(1：代表问题)
        messag.setCheckType(checkType);
        //描述
        String checkDescribe = replyAudit.getCheckDescribe();
        messag.setCheckDescribe(checkDescribe);
        //发送用户id
        int userId = replyAudit.getRUserId();
        messag.setUserId(userId);

        //添加站内消息
        messageMapper.addMessage(messag);

        //给问题发布者发送站内消息
        receiveQuestionMessag(checkState,title,content,question);

        log.info("站内消息发送完成 ^_^！");
        log.info("messag:{}",messag);
    }

    /**
     * 给问题发布者发送站内消息
     * @param checkState
     * @param title
     * @param content
     * @param question
     */
    public void receiveQuestionMessag(int checkState,String title,String content,Question question){
        //审核通过时给发表问题的用户发送站内消息
        if(checkState == 2){
            //创建站内消息
            Messag m = new Messag();

            //问题内容
            m.setTitle(title);
            //回答内容
            m.setContent(content);
            //描述
            m.setCheckDescribe("有人回答了您的问题 ^_^！");
            //发送用户id
            int uId = question.getQUserId();
            m.setUserId(uId);

            //添加站内消息
            messageMapper.addMessage(m);
        }
    }
}
